package xin.sparrow.dd.auth;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * @author wancheng  on 2018/9/3.
 */
public class DingTalkJsApiSingnature {
    public static String getJsApiSingnature(String url, String nonce, Long timeStamp, String jsTicket){
        String plainTex = "jsapi_ticket=" + jsTicket + "&noncestr=" + nonce + "&timestamp=" + timeStamp + "&url=" + url;
        System.out.println(plainTex);
        String signature = "";


        MessageDigest e = null;
        try {
            e = MessageDigest.getInstance("SHA-1");
            e.reset();
            e.update(plainTex.getBytes("UTF-8"));
            signature = byteToHex(e.digest());
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        return signature;

    }

    private static String byteToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        byte[] result = hash;
        int var3 = hash.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            byte b = result[var4];
            formatter.format("%02x", new Object[]{Byte.valueOf(b)});
        }

        String var6 = formatter.toString();
        formatter.close();
        return var6;
    }
}
